import socket

phone = socket.socket()

phone.bind(('127.0.0.1',8848))

phone.listen(2)
# listen: 2 允许有两个客户端加到半链接池，超过两个则会报错

while 1:
    conn,addr = phone.accept()  # 等待客户端链接我,阻塞状态中
    print(f'链接来了: {conn,addr}')

    while 1:
        try:
            from_client_data = conn.recv(1024)  # 最多接受1024字节

            if from_client_data.upper() == b'Q':
                print('客户端正常退出聊天了')
                break

            print(f'来自客户端{addr}消息:{from_client_data.decode("utf-8")}')
            to_client_data = input('>>>').strip().encode('utf-8')
            conn.send(to_client_data)
        except ConnectionResetError:
            print('客户端链接中断了')
            break
    conn.close()
phone.close()


